<template>
  <div class="home">
    <el-row :gutter="20">
      <el-col :span="6" v-for="(card, index) in dataCards" :key="card.title" class="fade-in" :style="{ animationDelay: `${index * 100}ms` }">
        <el-card 
          class="data-card"
        >
          <template #header>
            <div class="card-header">
              <el-icon><component :is="card.icon" /></el-icon>
              <span>{{ card.title }}</span>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ card.number }}</div>
            <div :class="['trend', card.trend]">
              <el-icon><component :is="card.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              <span>{{ card.percentage }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12" class="slide-in-left">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>交易趋势</span>
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="lineChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12" class="slide-in-right">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>分类销量</span>
              <el-switch
                v-model="barChartStack"
                active-text="堆叠"
                inactive-text="并列"
              />
            </div>
          </template>
          <div ref="barChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
            </div>
          </template>
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品评分分析</span>
            </div>
          </template>
          <div ref="radarChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>访问热力图</span>
            </div>
          </template>
          <div ref="heatmapChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import * as echarts from 'echarts'
import {
  Goods,
  ShoppingCart,
  User,
  ChatDotRound,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

// 数据卡片配置
const dataCards = [
  {
    title: '总商品数',
    number: 328,
    trend: 'up',
    percentage: 12.5,
    icon: 'Goods'
  },
  {
    title: '本月交易额',
    number: '¥23,800',
    trend: 'down',
    percentage: 5.2,
    icon: 'ShoppingCart'
  },
  {
    title: '活跃用户',
    number: 1280,
    trend: 'up',
    percentage: 8.4,
    icon: 'User'
  },
  {
    title: '消息数',
    number: 368,
    trend: 'up',
    percentage: 15.7,
    icon: 'ChatDotRound'
  }
]

const productStore = useProductStore()
const userStore = useUserStore()
const timeRange = ref('month')
const barChartStack = ref(false)

// 图表引用
const lineChartRef = ref<HTMLElement>()
const barChartRef = ref<HTMLElement>()
const pieChartRef = ref<HTMLElement>()
const radarChartRef = ref<HTMLElement>()
const heatmapChartRef = ref<HTMLElement>()

// 图表实例
let charts: echarts.ECharts[] = []

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    if (lineChartRef.value) {
      const lineChart = echarts.init(lineChartRef.value)
      lineChart.setOption(getLineChartOption())
      charts.push(lineChart)
    }

    if (barChartRef.value) {
      const barChart = echarts.init(barChartRef.value)
      barChart.setOption(getBarChartOption())
      charts.push(barChart)
    }

    if (pieChartRef.value) {
      const pieChart = echarts.init(pieChartRef.value)
      pieChart.setOption(getPieChartOption())
      charts.push(pieChart)
    }

    if (radarChartRef.value) {
      const radarChart = echarts.init(radarChartRef.value)
      radarChart.setOption(getRadarChartOption())
      charts.push(radarChart)
    }

    if (heatmapChartRef.value) {
      const heatmapChart = echarts.init(heatmapChartRef.value)
      heatmapChart.setOption(getHeatmapChartOption())
      charts.push(heatmapChart)
    }
  })
}

// 折线图配置
const getLineChartOption = () => ({
  tooltip: {
    trigger: 'axis',
    formatter: function(params: any) {
      const data = params[0]
      return `${data.name}<br/>交易额：¥${data.value[1]}`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'time',
    boundaryGap: false,
    axisLine: { lineStyle: { color: '#ddd' } }
  },
  yAxis: {
    type: 'value',
    axisLine: { lineStyle: { color: '#ddd' } },
    splitLine: { lineStyle: { color: '#eee' } }
  },
  series: [{
    name: '交易额',
    type: 'line',
    smooth: true,
    symbol: 'circle',
    symbolSize: 8,
    data: generateData(),
    itemStyle: { color: '#409eff' },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(64,158,255,0.3)' },
        { offset: 1, color: 'rgba(64,158,255,0.1)' }
      ])
    },
    animation: true,
    animationDuration: 1500,
    animationEasing: 'cubicInOut'
  }]
})

// 柱状图配置
const getBarChartOption = () => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' }
  },
  legend: {
    data: ['新商品', '已售出', '在售']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['电子产品', '服装', '图书', '生活用品']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '新商品',
      type: 'bar',
      stack: barChartStack.value ? '总量' : undefined,
      emphasis: {
        focus: 'series'
      },
      data: [120, 132, 101, 134]
    },
    {
      name: '已售出',
      type: 'bar',
      stack: barChartStack.value ? '总量' : undefined,
      emphasis: {
        focus: 'series'
      },
      data: [220, 182, 191, 234]
    },
    {
      name: '在售',
      type: 'bar',
      stack: barChartStack.value ? '总量' : undefined,
      emphasis: {
        focus: 'series'
      },
      data: [150, 232, 201, 154]
    }
  ],
  animation: true,
  animationDuration: 1500,
  animationEasing: 'elasticOut'
})

// 饼图配置
const getPieChartOption = () => ({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center'
  },
  series: [{
    name: '商品分类',
    type: 'pie',
    radius: ['50%', '70%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: { show: false },
    emphasis: {
      label: {
        show: true,
        fontSize: '16',
        fontWeight: 'bold'
      }
    },
    labelLine: { show: false },
    data: [
      { value: 335, name: '电子产品' },
      { value: 234, name: '服装' },
      { value: 158, name: '图书' },
      { value: 284, name: '生活用品' }
    ],
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: function () {
      return Math.random() * 200
    }
  }]
})

// 雷达图配置
const getRadarChartOption = () => ({
  tooltip: {
    trigger: 'item'
  },
  radar: {
    indicator: [
      { name: '商品质量', max: 100 },
      { name: '价格合理', max: 100 },
      { name: '物流速度', max: 100 },
      { name: '服务态度', max: 100 },
      { name: '用户满意', max: 100 }
    ]
  },
  series: [{
    name: '商品评分',
    type: 'radar',
    data: [
      {
        value: [85, 90, 75, 95, 88],
        name: '评分指标',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.3)' },
            { offset: 1, color: 'rgba(64,158,255,0.1)' }
          ])
        }
      }
    ],
    animation: true,
    animationDuration: 2000,
    animationEasing: 'bounceOut'
  }]
})

// 热力图配置
const getHeatmapChartOption = () => {
  const hours = ['12a', '1a', '2a', '3a', '4a', '5a', '6a',
    '7a', '8a', '9a', '10a', '11a',
    '12p', '1p', '2p', '3p', '4p', '5p',
    '6p', '7p', '8p', '9p', '10p', '11p']
  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

  const data = []
  for (let i = 0; i < 7; i++) {
    for (let j = 0; j < 24; j++) {
      data.push([j, i, Math.round(Math.random() * 100)])
    }
  }

  return {
    tooltip: {
      position: 'top',
      formatter: function (params: any) {
        return `${days[params.value[1]]} ${hours[params.value[0]]}<br>访问量: ${params.value[2]}`
      }
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '10%'
    },
    xAxis: {
      type: 'category',
      data: hours,
      splitArea: { show: true }
    },
    yAxis: {
      type: 'category',
      data: days,
      splitArea: { show: true }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '0%'
    },
    series: [{
      name: '访问量',
      type: 'heatmap',
      data: data,
      label: { show: false },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      animation: true,
      animationDuration: 1000,
      animationEasing: 'cubicOut'
    }]
  }
}

// 生成模拟数据
const generateData = () => {
  const data = []
  const today = new Date()
  for (let i = 29; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    data.push([
      date.toLocaleDateString(),
      Math.floor(Math.random() * 5000 + 1000)
    ])
  }
  return data
}

// 监听窗口大小变化
const handleResize = () => {
  charts.forEach(chart => chart.resize())
}

// 监听堆叠切换
watch(barChartStack, () => {
  if (barChartRef.value) {
    const barChart = echarts.init(barChartRef.value)
    barChart.setOption(getBarChartOption())
  }
})

onMounted(() => {
  setTimeout(() => {
    initCharts()
  }, 0)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  charts.forEach(chart => chart.dispose())
})
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.data-card .card-header {
  justify-content: flex-start;
  gap: 8px;
  color: #666;
}

.data-card .card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.data-card .number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.trend.up {
  color: #67c23a;
}

.trend.down {
  color: #f56c6c;
}

:deep(.el-card) {
  transition: all 0.3s;
}

:deep(.el-card:hover) {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

:deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 添加动画样式 */
.fade-in {
  animation: fadeIn 0.5s ease-out forwards;
  opacity: 0;
}

.slide-in-left {
  animation: slideInLeft 0.5s ease-out forwards;
  opacity: 0;
}

.slide-in-right {
  animation: slideInRight 0.5s ease-out forwards;
  opacity: 0;
}

.fade-in-up {
  animation: fadeInUp 0.5s ease-out forwards;
  opacity: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chart-container {
  height: 350px;
  width: 100%;
}
</style> 